/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.json.listeners;

import com.tencent.tendon.convert.util.*;
import com.tencent.tendon.convert.json.*;

/**
 *
 * @author nbzhang
 */
public final class JsonCharArrayListener extends JsonAbstractListener<char[]> {

    private static final JsonCharArrayListener instance = new JsonCharArrayListener();

    private static final JsonCharListener listener = JsonCharListener.getInstance();

    private JsonCharArrayListener() {
    }

    public static JsonCharArrayListener getInstance() {
        return instance;
    }

    @Override
    public char[] convertFrom(final JsonReader in) {
        final CharArray result = JsonPool.pollCharArray();
        in.checkArray();
        while (in.hasNext()) {
            result.add(listener.convertCharFrom(in));
        }
        char[] rs = result.toArray();
        JsonPool.offer(result);
        return rs;
    }

    @Override
    public final void convertTo(final JsonWriter out, final char[] value) {
        char[] values = value;
        if (values == null) {
            out.writeNull();
            return;
        }
        if (values.length == 0) {
            out.write('[', ']');
            return;
        }

        out.write('[');
        boolean first = true;
        for (char v : values) {
            if (!first) out.write(',');
            listener.convertCharTo(out, v);
            if (first) first = false;
        }
        out.write(']');
    }

    @Override
    public Class<char[]> getType() {
        return char[].class;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }

    public static final class JsonCharArrayHexListener extends JsonAbstractListener<char[]> {

        private static final JsonCharArrayHexListener instance = new JsonCharArrayHexListener();

        private JsonCharArrayHexListener() {
        }

        public static JsonCharArrayHexListener getInstance() {
            return instance;
        }

        @Override
        public void convertTo(JsonWriter out, char[] value) {
            if (value == null) {
                out.writeNull();
                return;
            }
            out.write('"');
            for (char ch : value) {
                if (ch == '"' || ch == '\t' || ch == '\r' || ch == '\n') out.write('\\');
                out.write(ch);
            }
            out.write('"');
        }

        @Override
        public char[] convertFrom(final JsonReader in) {
            return in.readValue();
        }

        @Override
        public Class<char[]> getType() {
            return char[].class;
        }
    }
}
